package com.wsh.study.service.impl;

import com.wsh.study.model.DataHistoryESModel;
import com.wsh.study.repository.DataHistoryESRepository;
import com.wsh.study.service.DataHistoryESService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DataHistoryESServiceImpl implements DataHistoryESService {

    @Autowired
    private DataHistoryESRepository dataHistoryESRepository;

    @Override
    public List<DataHistoryESModel> query(DataHistoryESModel model) {
        // Spring Data JPA 页码从0开始，页面减一
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(1 - 1, 10, sort);
        NativeSearchQueryBuilder query = new NativeSearchQueryBuilder().withPageable(pageable);
        if (model.getProjectId() != null) {
            query.withQuery(QueryBuilders.matchQuery("projectId", model.getProjectId()));
        }
        if (model.getModuleId() != null) {
            query.withQuery(QueryBuilders.matchQuery("moduleId", model.getModuleId()));
        }
        if (model.getCollectionId() != null) {
            query.withQuery(QueryBuilders.matchQuery("collectionId", model.getCollectionId()));
        }
        if (model.getDataNodeId() != null) {
            query.withQuery(QueryBuilders.matchQuery("dataNodeId", model.getDataNodeId()));
        }
        if (StringUtils.isNotBlank(model.getDataValue())) {
            query.withQuery(QueryBuilders.matchQuery("dataValue", model.getDataValue()));
        }
        if (model.getDataType() != null) {
            query.withQuery(QueryBuilders.matchQuery("dataType", model.getDataType()));
        }

        SearchQuery searchQuery = query.build();
        Page<DataHistoryESModel> pg = dataHistoryESRepository.search(searchQuery);
        if (pg.hasContent()) {
            return pg.getContent();

        }
        return null;
    }
}
